//
//  LGFSelectImageCollectionView.swift
//  MedicalUnion
//
//  Created by apple on 2019/8/26.
//  Copyright © 2019 William_Xue. All rights reserved.
//

import UIKit

protocol LGFSelectImageCollectionViewDelegate: class {
    func selectImageCollectionViewCount(view: LGFSelectImageCollectionView, imageArr: [UIImage]) -> Void
}
class LGFSelectImageCollectionView: UIView {

    weak var delegate: LGFSelectImageCollectionViewDelegate?
    
    var imageCV: UICollectionView!
    var line: UIView!
    
    var addImage: UIImage!
    var cellSize: CGSize!// cell Size
    var leftRightSpace: CGFloat!// 左右距离
    var maxCount: Int!// 图片最大数量
    var imageArr: [UIImage]! {
        didSet {
            self.delegate?.selectImageCollectionViewCount(view: self, imageArr: imageArr)
        }
    }// 图片数组
    var addImageArr: [UIImage]! {// 图片数组
        didSet {
            imageArr = addImageArr.filter { $0.lgf_Name != "添加" }
            if imageCV != nil {
                imageCV.reloadData()
            }
        }
    }
    var lineLeft: CGFloat! {// 底部线左侧距离
        didSet {
            if line != nil {
                line.transform = CGAffineTransform.identity
                line.transform = CGAffineTransform.init(translationX: lineLeft.lgf_W(), y: 0)
            }
        }
    }
    // 是否可编辑
    var isCanEdit: Bool! {
        didSet {
            self.isUserInteractionEnabled = isCanEdit
        }
    }
    
    class func lgf(imageArr: [UIImage],
                   addImage: UIImage!,
                   maxCount: Int,
                   cellSize: CGSize,
                   leftRightSpace: CGFloat,
                   canEdit: Bool,
                   lineLeft: CGFloat) -> LGFSelectImageCollectionView {
        let view: LGFSelectImageCollectionView = LGFSelectImageCollectionView.init()
        view.translatesAutoresizingMaskIntoConstraints = false
        if addImage != nil {
            view.addImage = addImage
            view.addImage.lgf_Name = "添加"
        }
        view.cellSize = cellSize
        view.leftRightSpace = leftRightSpace
        view.lineLeft = lineLeft
        view.maxCount = maxCount
        view.backgroundColor = UIColor.white
        view.addImageArr = view.addImage != nil ? [addImage] + imageArr : imageArr
        view.configView()
        view.isCanEdit = canEdit
        return view
    }
    
    func configView() {
        // 必选 *
        imageCV = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.lgf_ZeroSpacLayout(.vertical))
        imageCV.backgroundColor = UIColor.white
        imageCV.lgf_Register(cellType: LGFSelectImageCollectionViewCell.self)
        imageCV.delegate = self
        imageCV.dataSource = self
        addSubview(imageCV)
        imageCV.snp.makeConstraints { (make) in
            make.left.equalTo((leftRightSpace - 5).lgf_W())
            make.right.equalTo(-(leftRightSpace - 5).lgf_W())
            make.top.bottom.equalToSuperview()
        }
        
        // 底部线
        line = UIView.init()
        line.backgroundColor = UIColor.init(lgf_HexString: "F1F2F4")
        addSubview(line)
        line.transform = CGAffineTransform.init(translationX: lineLeft.lgf_W(), y: 0)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
    }
}

extension LGFSelectImageCollectionView: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: cellSize.width, height: cellSize.height)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return addImageArr.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: LGFSelectImageCollectionViewCell.self, for: indexPath)
        cell.image = addImageArr[indexPath.item]
        cell.deleteButton.isHidden = addImage == nil || indexPath.item == 0
        cell.delegate = self
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if addImageArr.count - (addImage != nil ? 1 : 0) < maxCount {
            if indexPath.item == 0 && addImage != nil {
                let imagePickerController =  TZImagePickerController.init(maxImagesCount: 10 - addImageArr.count + (addImage != nil ? 1 : 0), columnNumber: 3, delegate: self, pushPhotoPickerVc: true)
                UIApplication.shared.keyWindow?.rootViewController!.present(imagePickerController!, animated: true, completion: nil)
            }
        }
        if addImage != nil && indexPath.item > 0 {
            LGFShowImagesView.lgf(imageArr: addImageArr.filter { $0 != addImage }, selectIndex: indexPath.item, isShowDelete: false)
        } else if addImage == nil {
            LGFShowImagesView.lgf(imageArr: addImageArr, selectIndex: indexPath.item + 1, isShowDelete: false)
        }
    }
}

extension LGFSelectImageCollectionView: LGFSelectImageCollectionViewCellDelegate {
    func selectImageCollectionViewDelete(_ cell: LGFSelectImageCollectionViewCell) {
        addImageArr.remove(at: cell.tag)
    }
}

extension LGFSelectImageCollectionView: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        addImageArr += photos
    }
}

/// LGFSelectImageCollectionViewCell
protocol LGFSelectImageCollectionViewCellDelegate: class {
    func selectImageCollectionViewDelete(_ cell: LGFSelectImageCollectionViewCell) -> Void
}

class LGFSelectImageCollectionViewCell: UICollectionViewCell {
    
    weak var delegate: LGFSelectImageCollectionViewCellDelegate?
    
    var imageV: UIImageView!
    var deleteButton: UIButton!
    var image: UIImage! {
        didSet {
            if imageV != nil {
                imageV.image = image
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        
        imageV = UIImageView.init()
        imageV.contentMode = .scaleAspectFit
        imageV.clipsToBounds = true
        imageV.backgroundColor = UIColor.white
        addSubview(imageV)
        imageV.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 5.lgf_H(), left: 5.lgf_W(), bottom: 10.lgf_H(), right: 5.lgf_W()))
        }
        deleteButton = UIButton.init(type: .custom)
        deleteButton.setImage(#imageLiteral(resourceName: "image_delete"), for: .normal)
        addSubview(deleteButton)
        deleteButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.width.height.equalTo(15.lgf_W())
        }
        deleteButton.addTarget(self, action: #selector(deleteButtonClick), for: .touchUpInside)
    }
    
    @objc func deleteButtonClick() {
        self.delegate?.selectImageCollectionViewDelete(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

